<?php
namespace PsiFramework\Applications\AlloMediaPortal\Classes\Actions;

import("Classes.Actions.AbstractAction");
import("Classes.Util.HTTP.AuthenticationManager");
import("Classes.Factory.DAOFactory");
import("Applications.AlloMediaPortal.Classes.Model.AlloMediaEntry");

use \PsiFramework\Applications\AlloMediaPortal\Classes\Model\ResponseId;
use \PsiFramework\Classes\Actions\AbstractAction;
use \PsiFramework\Classes\Exceptions\SecurityException;
use \PsiFramework\Classes\Util\HTTP\AuthenticationManager;
use \PsiFramework\Classes\Util\Manager\ApplicationManager;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Util\UI\TemplateManager;
use \PsiFramework\Classes\Util\UI\ModuleManager;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Plugins\Form\Classes\DAO\FormResponseDAO;
use \PsiFramework\Classes\Util\HTTP\Session;
use \PsiFramework\Classes\Util\UI\HTML;
use \PsiFramework\Classes\Util\Object\Date;
use \PsiFramework\Plugins\Shop\Classes\Model\Order;


/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de l'index
 *
 * @package Actions.Pages
 */
abstract class AlloMediaUserAction extends AbstractAction
{

    protected /*Session*/ $_session;

    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
        
        $this->_session = Session::getInstance();
    }

    protected function calculateNote($entry)
    {
        $note = 0 ;
        $total = 0 ;
        $themePoints = array();
        
        if (!is_null($entry) && !is_null($entry->getCategory())) {
            $profile = $entry->getCategory()->getProfile();
            $parts = $profile->getParts();

            foreach ($parts as $part) {
                $theme = $part->getTheme();
                $total += $part->getPoints();

                $responseIdDao = DAOFactory::getDAO('ResponseId');
                $responseId
                    = $responseIdDao->retrieveByEntryAndTheme($entry, $theme);
                if (is_null($responseId)) {
                    $responseId = new ResponseId(null, $entry, $theme);
                    $responseIdDao->save($responseId);
                }

                $jsonForm = $theme->getStructure();

                $responseParameters = $theme->getResponseParameters();
                $formResponseDao
                    = FormResponseDAO::getInstance($responseParameters);

                if (!is_null($responseId)) {
                    $formResponse = $formResponseDao->retrieveByPk(
                        $responseId->getId(),
                        false,
                        true,
                        $responseId->getEntry()->getUser(),
                        $theme
                    );

                    if (!is_null($formResponse)
                        && !$formResponseDao->isEmpty(
                            $jsonForm,
                            $responseParameters,
                            $formResponse
                        )
                        && ($responseId->isActive() || $part->isFree())
                    ) {
                        $note += $part->getPoints();
                    } else {
                        $themePoints[]
                            = array(
                            		'theme'=>$theme,
                                    'responseId'=>$responseId,
                                    'part'=>$part
                            );
                    }
                }
            }
        }

        $this->_response->setAttribute('themePoints', $themePoints);
        $this->_response->setAttribute('totalPoints', $total);
        
        if ($total>0) {
        	$note = round(($note/$total)*100);
        } else {
        	$note = 0 ;
        }

        TemplateManager::getInstance()->addParameter('note', $note);
        
        $firstVisitCookieName = 'isFirstVisit';
        if ($note == 0 && isNullOrEmptyString($this->_session->getCookie($firstVisitCookieName))) {
            ModuleManager::getInstance()->addModule('FirstVisit', $this->_response);
            $expire = time() + (3600*24*31);
            $this->_session->setCookie($firstVisitCookieName, 'false', $expire);
        }
    }

    protected function retrieveEntries($user)
    {
        $filteredEntries = array();

        if (!is_null($user)) {
            $entries = $user->getEntries();
            if (!is_null($entries)) {
                foreach ($entries as $entry) {
                    $profile = $entry->getCategory()->getProfile();
                    if (!is_null($profile)) {
                        $filteredEntries[] = $entry ;
                    }
                }
            }
        }

        TemplateManager::getInstance()->
                         addParameter('entries', $filteredEntries);
    }

    public static function getCurrency(/*boolean*/ $checkSecurity=true)
    {
        $currency = Session::getInstance()->get('Currency');
        if (is_null($currency)) {
        	$currencyIso = ApplicationManager::getInstance()->getApplication()->getParameter('currency');
        	$currencyDao = DAOFactory::getDAO('Currency');
        	$currency = $currencyDao->retrieveByIso($currencyIso, $checkSecurity);
        	Session::getInstance()->set('Currency', $currency);
        }
        
        return $currency;
    }
    
    public static function getPaymentParamsList()
    {
        $params
            = array(
        		'ACCEPTANCE',
        		'amount',
        		'BRAND',
        		'CARDNO',
        		'CN',
        		'currency',
        		'ED',
        		'IP',
        		'NCERROR',
        		'orderID',
        		'PAYID',
        		'PM',
        		'STATUS',
        		'TRXDATE'
            );
        
        return $params;
    }
    
    public static function getPaymentPassword()
    {
        return ApplicationManager::getInstance()->getApplication()->getParameter('paymentPassword');
    }
    
    public static function getPaymentUrl()
    {
    	return ApplicationManager::getInstance()->getApplication()->getParameter('paymentUrl');
    }
    
    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     *@return void
     */
    public function execute()
    {
        parent::execute();
        
        $userDao = DAOFactory::getDAO('User');
        $this->_user->setLastConnection(Date::now());
        $userDao->save($this->_user);
        
        $currency = self::getCurrency();
        $this->_response->setAttribute('Currency', $currency);
        
        $entryId = $this->_request->getParameter('entry_id');
        $entry = null ;

        if (!isNullOrEmptyString($entryId)) {
            $entryDao = DAOFactory::getDAO('AlloMediaEntry');
            $entry = $entryDao->retrieveByPk($entryId);
            if (is_null($entry)) {
                throw new \Exception("Impossible de récupérer l'entrée !");
            }
        } else {
            $entry = $this->_session->get('entry');
            if (!is_null($entry) && $entry->getUser()->getId() != $this->_user->getId()) {
                $entry = null;
            }
        }

        if (!is_null($this->_user)) {
            $entries = $this->_user->getEntries();
            $ok = false ;
            if (!is_null($entries) && count($entries)>0) {
                if (is_null($entry)) {
                    $entry = $entries[0] ;
                    $ok = true ;
                } else {
                    foreach ($entries as $curEntry) {
                        if ($entry->getId() == $curEntry->getId()) {
                            $ok = true ;
                            break;
                        }
                    }
                }
            }

            if (!$ok) {
                throw new SecurityException(
                    "Vous ne pouvez pas voir cette entrée !"
                );
            }

        }

        $category = null ;
        if (!is_null($entry)) {
        	$category = $entry->getCategory();
        }
        if (is_null($category)) {
            $categoryId = $this->_request->getParameter('category_id');
            if (!is_null($categoryId)) {
                $categoryDao = DAOFactory::getDAO('SiteCategory');
                $category = $categoryDao->retrieveByPk($categoryId);
            }
        }

        if (!is_null($category)) {
            $style = $category->getStyle();
            if (!is_null($style)) {
                $css = $style->getCss();
                if (!isNullOrEmptyString($css)) {
                    TemplateManager::getInstance()->addLitteralStyle($css);
                }
            }
        }

        TemplateManager::getInstance()->setTitle($entry->getName());

        TemplateManager::getInstance()->addRemoteScript(
    		'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'
        );
        TemplateManager::getInstance()->addRemoteScript(
    		'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js'
        );
        TemplateManager::getInstance()->addFileScript(
            'Applications/DefaultApp/Template/scripts/jquery.jscrollpane.min.js'
        );
        TemplateManager::getInstance()->addFileScript(
    		'Applications/DefaultApp/Template/scripts/jquery.mousewheel.js'
        );
        TemplateManager::getInstance()->addFileScript(
    		'Applications/DefaultApp/Template/scripts/mwheelIntent.js'
        );
        TemplateManager::getInstance()->addFileScript(
    		'Applications/DefaultApp/Template/scripts/jquery.simplemodal.js'
        );
        
        TemplateManager::getInstance()->addLitteralScript(
    		"
            function updateTotal(quantity, price, discount, percentage){
            	var normalTotal = (quantity*price);
                var total = normalTotal;
            	if(discount != undefined && discount != null){
                	if(percentage) total = quantity*price*(1-(discount/100));
                	else total = (quantity*price)-discount;

                    reduction = normalTotal-total;
                	$('#item_discount').html('(Soit '+reduction.toFixed(2)+'".$currency->getSymbol()." d\'économie)'); 
            	} else {
                    $('#item_discount').html(''); 
                }
                
            	$('#item_total').html(total.toFixed(2) + '".$currency->getSymbol()."');
            }
                
            function unlockTheme(form, entry){
                link  = '".HTML::linkHref('action=AjaxOrderTheme')."';
                link += '&entry_id='+entry;
                link += '&form_id='+form;
                $.ajax({
                    url: link,
                    type: 'GET',
                    cache: false,
                    timeout: 60000,
                    error: function() {
                        alert('Erreur lors de la récupération du panier !');
                    },
                    success: function(data) { 
                        $('#boxshadow-confirmation').html(data);
                    	$('#boxshadow-confirmation').modal({
        					opacity:80,
        					overlayCss:{backgroundColor:'#000'},
        					minWidth:576,
        					minHeight:340,
                            maxWidth:576,
        					maxHeight:340,
                            closeClass:'confirmation-close',
        					overlayClose:true
        				});
        				return false;
                    }
                });
            }
                
            $(document).ready(function(){
    			$('.scroll-pane').jScrollPane();
    		});"
        );
        
        $this->calculateNote($entry);
        $this->retrieveEntries($this->_user);

        $this->_response->setAttribute("entry", $entry);
        $this->_session->set('entry', $entry);
        
        $this->_response->setAttribute("category", $category);

        $this->_response->setAttribute("user", $this->_user);

        ModuleManager::getInstance()->addModule('TopMenu', $this->_response);
        ModuleManager::getInstance()->addModule('BottomMenu', $this->_response);
        ModuleManager::getInstance()->addModule('WelcomeBanner', $this->_response);
        ModuleManager::getInstance()->addModule('BasketTotal', $this->_response);
        ModuleManager::getInstance()->addModule('BasketDetail', $this->_response);
        ModuleManager::getInstance()->addModule('Trace', $this->_response);
        
        $status = null;
        $shaSign = $this->_request->getParameter('SHASIGN');
        if (!isNullOrEmptyString($shaSign)) {
            $password = self::getPaymentPassword();
            $params = self::getPaymentParamsList();
            
            $shaString = '';
            foreach ($params as $paramName) {
            	$paramValue = $this->_request->getParameter($paramName);
            	$shaString .= strtoupper($paramName).'='.$paramValue.$password;
            }
            $calculatedSha = strtoupper(sha1($shaString));
            
            if ($shaSign == $calculatedSha) {
                $status = $this->_request->getParameter('STATUS');
                
                $orderNumber = $this->_request->getParameter('orderID');
                $orderDao = DAOFactory::getDAO('Order');
                $order = $orderDao->retrieveByNumber($orderNumber, false, false);
                $order->setStatus($status);
                $order->setMeanOfPayment('CREDIT_CARD');
                $orderDao->save($order);
                
                $this->_response->setAttribute('step', 4);
                ModuleManager::getInstance()->addModule('Steps', $this->_response);
            }
        }
        
        if (!is_null($status) && $status == Order::$paymentRequested['code']) {
            
            ModuleManager::getInstance()->addModule('PaymentAlert', $this->_response);
            TemplateManager::getInstance()->addLitteralScript(
                "
                $(document).ready(function(){
    				$('#boxshadow-alerte').modal({
    					opacity:80,
    					overlayCss:{backgroundColor:\"#000\"},
    					minWidth:400,
    					minHeight:150,
    					maxWidth:400,
    					maxHeight:150,
    					closeClass:'alerte-close',
    					overlayClose:true
    				});
                    $('#boxshadow-alerte').css('display', 'block');
                    $('#boxshadow-alerte').show();
        		});
                "
            );
        }
    }
}
